﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WJP.DataPortal.WCF;
using WJP.WCF;

namespace WJP.DataPortal
{
    /// <summary>
    /// 最终调用实体的 IDataPortalServer 门户实现。
    /// </summary>
    internal class FinalDataPortal : IDataPortalServer
    {
        /// <summary>
        /// 调用某个类型的查询方法以返回它的数据
        /// </summary>
        /// <param name="objectType"></param>
        /// <param name="criteria"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public DataPortalResult Fetch(Type objectType, object criteria, DataPortalContext context)
        {
            return new DataPortalResult(Fetch(objectType, criteria));
        }

        /// <summary>
        /// 直接更新某个对象
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public DataPortalResult Update(object obj, DataPortalContext context)
        {
            Update(obj);
            return new DataPortalResult(obj);
        }

        /// <summary>
        /// 调用某个类型的查询方法以返回它的数据
        /// </summary>
        /// <param name="objectType"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        internal static object Fetch(Type objectType, object criteria)
        {
            IPortalFetchable portalFetchable = null;
            if (objectType.IsSubclassOf(typeof(DomainController)))
                portalFetchable = Dependency.IocManager.Instance.Resolve(objectType) as IPortalFetchable;
            //TODO:仓库查询
            return portalFetchable.Fetch(criteria);
        }

        /// <summary>
        /// 直接更新某个对象
        /// </summary>
        /// <param name="obj"></param>
        internal static void Update(object obj)
        {
            if (obj == null)
                throw new ArgumentNullException(nameof(obj));
            if (!(obj is IPortalUpdatable portalUpdatable))
                throw new DataPortalException("{0}没实现IPortalFetchable接口".FormatArgs((object)obj.GetType().FullName));
            portalUpdatable.Update();
        }

        internal static ApiResponse Invoke(ApiRequest request)
        {
            //TODO: 实现API调用

            return new ApiResponse();
        }
    }
}
